package com.natalia.excel.validate.enums;

import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;

/**
 * @Author yang
 **/
public class EnumValidator implements ConstraintValidator<EnumValidation, Object> {

    EnumValidation enumValidation;

    @Override
    public void initialize(EnumValidation constraintAnnotation) {
        this.enumValidation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (ObjectUtils.isEmpty(value)) {
            if (enumValidation.nullable()) {
                return true;
            }
            return false;
        }
        Object[] objects = enumValidation.clazz().getEnumConstants();
        try {
            Method method = enumValidation.clazz().getMethod(enumValidation.method());
            for (Object o : objects) {
                if (value.equals(method.invoke(o))) {
                    return true;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}